import util from "./util"
import userInfo from "../src/utils/userInfo";
const BaseUrl = 'https://api.dailihoutai.dt12.cfd/api';//https://test.houtai.bond/api/   //http://api.dailihoutai.dt12.cfd/api 

// 请求队列（处理token刷新时的并发请求）
let refreshPromise = null;
let pendingRequests = [];

// 核心请求方法
export const Request = async (options = {}) => {
	const {
		url = '',
			data = {},
			method = 'GET',
			timeout = 15000, // App端建议更长的超时
			retryCount = 1 // 自动重试次数
	} = options;
	// 动态域名处理
	const fullUrl =  userInfo.globalUserInfo.extraUrl?
		userInfo.globalUserInfo.extraUrl + url :
		BaseUrl + url;

	// 请求头
	const header = {
		"content-type": "application/json",//application/x-www-form-urlencoded;charset=UTF-8;
		// "Authorization": util.getToken(),
		"token": util.getToken(),
		...(options.header || {})
	};

	// 网络状态检测
	const networkType = await checkNetwork();
	if (networkType === 'none') {
		return Promise.reject({
			code: 'NETWORK_ERROR',
			msg: '网络不可用'
		});
	}

	try {
		const response = await uniRequest(fullUrl, method, data, header, timeout);
		return handleResponse(response);
	} catch (error) {
		// Token过期处理
		if (error.statusCode === 401 && retryCount > 0) {
			return handleTokenRefresh(options, retryCount);
		}

		// 其他错误处理
		if (error.code !== 'NETWORK_ERROR') {
			uni.showToast({
				title: error.msg || '请求失败',
				icon: 'none'
			});
		}
		throw error;
	}
};

// 处理token刷新
const handleTokenRefresh = async (options, retryCount) => {
	// 避免重复刷新
	if (!refreshPromise) {
		refreshPromise = util.refresh();
	}

	try {
		const refreshSuccess = await refreshPromise;
		if (refreshSuccess) {
			// 刷新成功，重试原请求
			return Request({
				...options,
				retryCount: retryCount - 1
			});
		} else {
			// 刷新失败跳转登录
			util.toLogin();
			return Promise.reject({
				code: 'AUTH_EXPIRED',
				msg: '请重新登录'
			});
		}
	} finally {
		refreshPromise = null;
	}
};

// 封装uni.request
const uniRequest = (url, method, data, header, timeout) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			method,
			data,
			header,
			timeout,
			success: resolve,
			fail: reject
		});
	});
};

// 响应处理
const handleResponse = (res) => {
	const {
		statusCode,
		data
	} = res;

	// 成功状态
	if (statusCode >= 200 && statusCode < 300) {
		// 特殊错误码处理
		if ([1000, 5000].includes(data?.code)) {
			uni.showToast({
				title: data.msg,
				icon: 'none'
			});
		}
		return data;
	}

	// 错误处理
	const error = {
		statusCode,
		code: data?.code || 'UNKNOWN_ERROR',
		msg: data?.msg || `请求错误: ${statusCode}`
	};

	// 401处理 - 在catch中统一处理
	if (statusCode === 401) {
		error.code = 'TOKEN_EXPIRED';
	}

	throw error;
};

// 网络检测
const checkNetwork = () => {
	return new Promise(resolve => {
		uni.getNetworkType({
			success: (res) => resolve(res.networkType),
			fail: () => resolve('unknown')
		});
	});
};

// 封装常用方法
export const Get = (url, params) => Request({
	url,
	data: params
});
export const Post = (url, data) => Request({
	url,
	data,
	method: 'POST'
});
export const Put = (url, data) => Request({
	url,
	data,
	method: 'PUT'
});
export const Delete = (url) => Request({
	url,
	method: 'DELETE'
});